import React, { memo, useEffect, useState } from "react";
import { getList } from "../Api/getList";
import { Image, Button } from "react-vant";

const Car = memo(() => {
  // 杯型
  let [arr, setArr] = useState([]);
  let [idOne, setidOne] = useState(0);
  // 温度
  let [wen, setWen] = useState([]);
  let [idTwo, setidTwo] = useState(0);
  // 糖度
  let [tang, setTang] = useState([]);
  let [idThree, setidThree] = useState(0);

  let [obj, setObj] = useState();
  // 动态改变杯型的函数
  const beiT = (id) => {
    setidOne(id);
  };
  // 动态改变温度
  const wenT = (id) => {
    setidTwo(id);
  };
  // 动态改变糖度
  const tangT = (id) => {
    setidThree(id);
  };
  // 点击立即购买
  const submit = () => {
    setObj({
      id: Date.parse(new Date()),
      beiType: arr.find((item) => item.id === idOne).name,
      wenType: wen.find((item) => item.id === idTwo).name,
      tangType: tang.find((item) => item.id === idThree).name,
    });
    console.log(obj);
  };
  // 封装函数 并发送axios请求获取数据
  const get = async () => {
    let res = await getList();
    setArr(res.data.type);
    setWen(res.data.wendu);
    setTang(res.data.tangdu);
  };
  // 页面挂载完 调用获取数据的函数 获取数据
  useEffect(() => {
    get();
  }, []);

  // 封装子组件部分
  const Tab = (props) => {
    const { newArr, huo } = props;
    const [num, setNum] = useState(0);
    // 点击事件
    const Tab = (id, index) => {
      setNum(index);
      huo(id);
    };
    return (
      <>
        {newArr.map((item, index) => {
          return (
            <Button
              type="primary"
              size="mini"
              key={item.id}
              color={num === index ? "pink" : "skyblue"}
              onClick={() => Tab(item.id, index)}
            >
              {item.name}
            </Button>
          );
        })}
      </>
    );
  };

  return (
    <div>
      {/* 图片部分 */}
      <div>
        <Image
          width="100%"
          height="2  00"
          src={
            "https://jmy-pic.baidu.com/0/pic/984139413_464210325_720960145.jpg@f_webp"
          }
        />
      </div>
      {/* 选项卡部分 */}
      <div>
        <h3>杯型</h3>
        <Tab newArr={arr} huo={beiT}></Tab>
      </div>
      <div>
        <h3>温度</h3>
        <Tab newArr={wen} huo={wenT}></Tab>
      </div>
      <div>
        <h3>糖度</h3>
        <Tab newArr={tang} huo={tangT}></Tab>
      </div>
      <p></p>
      <Button type="primary" block round onClick={() => submit()}>
        块级元素
      </Button>
    </div>
  );
});

export default Car;
